package com.gameplatform.service;

import com.gameplatform.model.Rating;
import com.gameplatform.util.DBUtil;

import java.sql.*;

public class RatingService {

    public boolean createRating(Rating rating) {
        Connection conn = null;

        try {
            conn = DBUtil.getConnection();
            conn.setAutoCommit(false);

            // 检查用户是否已经评分过
            String checkSql = "SELECT id FROM ratings WHERE game_id = ? AND user_id = ?";
            PreparedStatement checkStmt = conn.prepareStatement(checkSql);
            checkStmt.setInt(1, rating.getGameId());
            checkStmt.setInt(2, rating.getUserId());
            ResultSet rs = checkStmt.executeQuery();

            String sql;
            PreparedStatement stmt;

            if (rs.next()) {
                // 更新现有评分
                sql = "UPDATE ratings SET rating = ?, create_time = NOW() WHERE game_id = ? AND user_id = ?";
                stmt = conn.prepareStatement(sql);
                stmt.setInt(1, rating.getRating());
                stmt.setInt(2, rating.getGameId());
                stmt.setInt(3, rating.getUserId());
            } else {
                // 插入新评分
                sql = "INSERT INTO ratings (game_id, user_id, rating, create_time) VALUES (?, ?, ?, NOW())";
                stmt = conn.prepareStatement(sql);
                stmt.setInt(1, rating.getGameId());
                stmt.setInt(2, rating.getUserId());
                stmt.setInt(3, rating.getRating());
            }

            int result = stmt.executeUpdate();

            if (result > 0) {
                // 更新游戏的平均评分
                updateGameRating(conn, rating.getGameId());
                conn.commit();
                return true;
            } else {
                conn.rollback();
                return false;
            }
        } catch (SQLException e) {
            e.printStackTrace();
            try {
                if (conn != null) {
                    conn.rollback();
                }
            } catch (SQLException ex) {
                ex.printStackTrace();
            }
            return false;
        } finally {
            try {
                if (conn != null) {
                    conn.setAutoCommit(true);
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
            DBUtil.closeConnection(conn);
        }
    }

    private void updateGameRating(Connection conn, int gameId) throws SQLException {
        String sql = "UPDATE games SET average_rating = (SELECT AVG(rating) FROM ratings WHERE game_id = ?), rating_count = (SELECT COUNT(*) FROM ratings WHERE game_id = ?) WHERE id = ?";
        PreparedStatement stmt = conn.prepareStatement(sql);
        stmt.setInt(1, gameId);
        stmt.setInt(2, gameId);
        stmt.setInt(3, gameId);
        stmt.executeUpdate();
    }
}